package com.mt.grand.delegate.mvc;

import com.mt.grand.delegate.mvc.controller.LoginController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class ServlectDispatcher {

    private List<Handler> handlerMapping = new ArrayList<>();

    public ServlectDispatcher(){
        try {
            Class<?> loginControllerClass = LoginController.class;
        handlerMapping.add(new Handler()
                        .setController(loginControllerClass.newInstance())
                        .setMethod(loginControllerClass.getMethod("login",null))
                        .setUrl("/sys/login"));
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void doService(HttpServletRequest request, HttpServletResponse response) throws InvocationTargetException, IllegalAccessException {
        dispatcher(request,response);
    }

    private void dispatcher(HttpServletRequest request, HttpServletResponse response) throws InvocationTargetException, IllegalAccessException {
        String uri = request.getRequestURI();
        Handler handle = null;
        for (Handler h:handlerMapping) {
            if(uri.equals(h.getUrl())){
                handle = h;
                break;
            }
        }
        Object object = null;
        object = handle.getMethod().invoke(handle.getController(),request.getParameter("loginId"));
    }

    class Handler {

        private String url;
        private Method method;
        private Object controller;

        public String getUrl() {
            return url;
        }

        public Handler setUrl(String url) {
            this.url = url;
            return this;
        }

        public Method getMethod() {
            return method;
        }

        public Handler setMethod(Method method) {
            this.method = method;
            return this;
        }

        public Object getController() {
            return controller;
        }

        public Handler setController(Object controller) {
            this.controller = controller;
            return this;
        }
    }
}